package com.warm.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.warm.cache.utils.CacheUtil;
import com.warm.core.constant.CacheConstants;
import com.warm.core.constant.HttpStatus;
import com.warm.core.domain.AjaxResult;
import com.warm.core.page.BaseController;
import com.warm.core.page.TableDataInfo;
import com.warm.core.utils.StringUtils;
import com.warm.domain.SysUserOnline;
import com.warm.log.annotation.Log;
import com.warm.log.enums.BusinessType;
import com.warm.service.ISysUserOnlineService;
import com.warm.system.api.LoginUser;
import org.noear.solon.annotation.*;
import org.noear.solon.validation.annotation.Valid;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 在线用户监控
 *
 * @author warm
 */
@Valid
@Controller
@Mapping("/monitor/online")
public class SysUserOnlineController extends BaseController {
    @Inject
    private ISysUserOnlineService userOnlineService;

    @SaCheckPermission("monitor:online:list")
    @Get
    @Mapping("/list")
    public TableDataInfo<SysUserOnline> list(String ipaddr, String userName) {
        List<String> keys = StpUtil.searchTokenValue("", 0, -1, false);
        List<SysUserOnline> userOnlineList = new ArrayList<>();
        for (String key : keys) {
            String token = StringUtils.substringAfterLast(key, ":");
            // 如果已经过期则跳过
            if (StpUtil.stpLogic.getTokenActiveTimeoutByToken(token) < -1) {
                continue;
            }
            LoginUser user = CacheUtil.getCacheObject(CacheConstants.ONLINE_TOKEN_KEY + ":" + token, LoginUser.class);
            if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) {
                userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
            } else if (StringUtils.isNotEmpty(ipaddr)) {
                userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
            } else if (StringUtils.isNotEmpty(userName) && ObjectUtil.isNotNull(user.getUser())) {
                userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
            } else {
                userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
            }
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        return getDataTable(userOnlineList);
    }

    /**
     * 强退用户
     */
    @SaCheckPermission("monitor:online:forceLogout")
    @Log(title = "在线用户", businessType = BusinessType.FORCE)
    @Delete
    @Mapping("/{tokenId}")
    public AjaxResult forceLogout(String tokenId) {
        CacheUtil.deleteObject(CacheConstants.ONLINE_TOKEN_KEY + ":" + tokenId);
        StpUtil.kickoutByTokenValue(tokenId);
        return success();
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static <T> TableDataInfo<T> getDataTable(List<T> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(list.size());
        return rspData;
    }
}
